import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '../router'
import { getToken } from '@/utils/auth'

const initAxios = axios.create({
  timeout: 1000 * 30,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})
 
// 请求拦截器
initAxios.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (getToken()) {
      config.headers['authtoken'] = getToken()
    }
    return config
  }, (error: any) => {
    return Promise.reject(error)
  }
)
 
// 响应拦截器
initAxios.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response?.status === 200 ) {
      if (response.data) {
        const { code, error } = response.data
        // 接口编码
        if (code === 200) {
          return response.data
        } else {
          if (code === 301) {
            ElMessageBox.confirm(error, '警告', {
              confirmButtonText: '重新登陆',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              router.push({
                path: '/login'
              })
            })
          } else {
            ElMessage.error(response.statusText)
            return Promise.reject(response.data)
          }
        }
      }
    } else {
      ElMessage.error(response.statusText)
      return Promise.reject(response.statusText)
    }
  }, error => {
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)

// 导出
export default () => initAxios